package com.fine.hair.manage.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fine.hair.comm.dto.*;
import com.fine.hair.comm.exception.BusinessException;
import com.fine.hair.comm.model.*;
import com.fine.hair.comm.utils.ApiResponse;
import com.fine.hair.comm.utils.PageInfo;
import com.fine.hair.comm.vo.InventoryPageVo;
import com.fine.hair.comm.vo.InventoryPutRecordVo;
import com.fine.hair.comm.vo.InventoryReceiveRecordVo;
import com.fine.hair.manage.mapper.*;
import com.fine.hair.manage.util.JwtUtil;
import io.jsonwebtoken.lang.Collections;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>库存相关接口</p>
 *
 * @author mouseyCat
 * @date 2020/11/17 11:11
 */


@Api(tags = {"库存相关接口"})
@RestController
@RequestMapping("/inventory/")
public class InventoryController {

    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private SecUserMapper secUserMapper;

    @Autowired
    private Snowflake snowflake;

    @Autowired
    private InventoryMapper inventoryMapper;

    @Autowired
    private BranchMapper branchMapper;

    @Autowired
    private InventoryPutRecordMapper inventoryPutRecordMapper;

    @Autowired
    private InventoryReceiveRecordMapper inventoryReceiveRecordMapper;

    @ApiOperation("列表--库存分页列表")
    @PostMapping("page")
    public ApiResponse<PageInfo<InventoryPageVo>> inventoryPage(HttpServletRequest request, @Validated @RequestBody InventoryPageDto dto) {
        List<Branch> branches = branchMapper.selectList(new LambdaQueryWrapper<Branch>().select(Branch::getId,
                Branch::getTitle));
        // 判断用户是不是门店管理员
        String username = jwtUtil.getUsernameFromJWT(jwtUtil.getJwtFromRequest(request));
        SecUser secUser = secUserMapper.selectByUsername(username);
        List<Branch> result;

        if (Objects.isNull(secUser.getBranchId())) {
            result = branches;
        } else {
            result = branches.stream().filter(b -> b.getId().equals(secUser.getBranchId())).collect(Collectors.toList());
        }
        dto.setBranchId(secUser.getBranchId());
        PageInfo<InventoryPageVo> objectPageInfo = new PageInfo<>(dto.getPageCurr(), dto.getPageSize());
        List<String> branchIds;
        if(Collections.isEmpty(result)){
            branchIds = null;
        }else {
            branchIds = result.stream().map(b->String.valueOf(b.getId())).collect(Collectors.toList());
        }
        // TODO sql1 列表 sql2 最后入库时间
        List<InventoryPageVo> list = inventoryMapper.list(dto, branchIds,objectPageInfo);
        for (InventoryPageVo inventoryPageVo : list) {
            List<InventoryPutRecord> inventoryPutRecords =
                    inventoryPutRecordMapper.selectList(new LambdaQueryWrapper<InventoryPutRecord>().eq(InventoryPutRecord::getInventoryId, inventoryPageVo.getId()).orderByDesc(InventoryPutRecord::getCreateTime));
            if (inventoryPutRecords.size() < 1) {
                inventoryPageVo.setLastPutTime("暂无入库记录");
            } else {
                inventoryPageVo.setLastPutTime(DateUtil.formatDateTime(inventoryPutRecords.get(0).getCreateTime()));
            }
        }
        objectPageInfo.setRecords(list);
        return ApiResponse.ofSuccess(objectPageInfo);
    }

    @ApiOperation("列表--当前物品入库分页列表--详情页面")
    @PostMapping("putRecord/page")
    public ApiResponse<PageInfo<InventoryPutRecordVo>> inventoryPutRecord(@Validated @RequestBody InventoryPutRecordDto dto) {

        PageInfo<InventoryPutRecordVo> objectPageInfo = new PageInfo<>(dto.getPageCurr(), dto.getPageSize());
        // TODO sql
        List<InventoryPutRecordVo> list = inventoryPutRecordMapper.list(dto, objectPageInfo);
        objectPageInfo.setRecords(list);
        return ApiResponse.ofSuccess(objectPageInfo);
    }

    @ApiOperation("列表--当前物品领用记录分页列表--详情页面")
    @PostMapping("receiveRecord/page")
    public ApiResponse<PageInfo<InventoryReceiveRecordVo>> inventoryReceiveRecord(@Validated @RequestBody InventoryReceiveRecordDto dto) {
        PageInfo<InventoryReceiveRecordVo> objectPageInfo = new PageInfo<>(dto.getPageCurr(), dto.getPageSize());
        // TODO sql
        List<InventoryReceiveRecordVo> list = inventoryReceiveRecordMapper.list(dto, objectPageInfo);
        objectPageInfo.setRecords(list);
        return ApiResponse.ofSuccess(objectPageInfo);
    }

    @ApiOperation("内容--获取物品基本信息--物品详情页面")
    @PostMapping("detail")
    public ApiResponse<InventoryPageVo> inventoryDetail(@Validated @RequestBody InventoryDetailDto dto) {
        Inventory inventory = inventoryMapper.selectById(dto.getId());
        if (inventory == null) {
            throw new BusinessException("当前物品不存在");
        }
        InventoryPageVo inventoryPageVo = new InventoryPageVo();
        inventoryPageVo.setId(inventory.getId());
        inventoryPageVo.setImg(inventory.getImg());
        inventoryPageVo.setName(inventory.getName());
        inventoryPageVo.setSpecification(inventory.getSpecification());
        inventoryPageVo.setSum(inventory.getSum());
        // TODO sql最后一次入库时间
        List<InventoryPutRecord> inventoryPutRecords =
                inventoryPutRecordMapper.selectList(new LambdaQueryWrapper<InventoryPutRecord>().eq(InventoryPutRecord::getInventoryId, dto.getId()).orderByDesc(InventoryPutRecord::getCreateTime));
        if (inventoryPutRecords.size() < 1) {
            inventoryPageVo.setLastPutTime("暂无入库记录");
        } else {
            inventoryPageVo.setLastPutTime(DateUtil.formatDateTime(inventoryPutRecords.get(0).getCreateTime()));
        }
        return ApiResponse.ofSuccess(inventoryPageVo);
    }

    @ApiOperation("功能--入库操作")
    @PostMapping("add")
    @Transactional(rollbackFor = Exception.class)
    public ApiResponse inventoryAdd(@Validated @RequestBody InventoryAddDto dto) {
        //Inventory inventory = inventoryMapper.selectOneLikeName(dto);
        Inventory inventory = inventoryMapper.selectOne(new LambdaQueryWrapper<Inventory>().eq(Inventory::getId,
                dto.getInventoryId()));

        if (ObjectUtil.isNotNull(inventory)) {
            // TODO 叠加物品数量
            inventory.setSum(inventory.getSum() + dto.getSum());
            inventoryMapper.updateById(inventory);
        } else {
            // TODO 新增物品
            inventory = new Inventory();
            inventory.setId(snowflake.nextId());
            inventory.setName(dto.getName());
            inventory.setImg(dto.getImg());
            inventory.setSpecification(dto.getSpecification());
            inventory.setSum(dto.getSum());
            inventory.setBranchId(dto.getBranchId());
            inventoryMapper.insert(inventory);
        }
        // TODO 新增入库记录
        InventoryPutRecord inventoryPutRecord = new InventoryPutRecord();
        inventoryPutRecord.setId(snowflake.nextId());
        inventoryPutRecord.setCount(dto.getSum());
        inventoryPutRecord.setBranchId(Long.valueOf(dto.getBranchId()));
        inventoryPutRecord.setInventoryId(inventory.getId());
        inventoryPutRecord.setRemark(dto.getRemark());
        inventoryPutRecord.setTotalMoney(dto.getMoney().multiply(new BigDecimal(dto.getSum())));
        inventoryPutRecord.setMoney(dto.getMoney());
        SecUser secUser = secUserMapper.selectById(dto.getUserId());
        if (secUser == null) {
            throw new BusinessException("当前用户不存在");
        }
        inventoryPutRecord.setUserName(secUser.getUsername());
        inventoryPutRecordMapper.insert(inventoryPutRecord);
        return ApiResponse.ofSuccess();
    }

    @ApiOperation("功能--入库前，检测当前物品是否在库里存在,true-存在,弹出提示框 false-不存在")
    @PostMapping("detectBeforeAdd")
    public ApiResponse<Boolean> detectBeforeAdd(@RequestBody DetectBeforeAddDto dto) {
        Inventory inventory = inventoryMapper.selectOneLikeName(dto);
        if (ObjectUtil.isNotNull(inventory)) {
            return ApiResponse.ofSuccess(true);
        } else {
            return ApiResponse.ofSuccess(false);
        }
    }


    @ApiOperation("功能--领用库存物品操作")
    @PostMapping("takeOut")
    public ApiResponse inventoryTakeOut(@Validated @RequestBody InventoryTakeOutDto dto) {
        Inventory inventory = inventoryMapper.selectById(dto.getId());
        if (inventory == null) {
            throw new BusinessException("当前物品不存在");
        }
        if (dto.getCount() > inventory.getSum()) {
            throw new BusinessException("领用数量不可大于总库存量");
        }
        inventory.setSum(inventory.getSum() - dto.getCount());
        inventoryMapper.updateById(inventory);
        InventoryReceiveRecord inventoryReceiveRecord = new InventoryReceiveRecord();
        inventoryReceiveRecord.setId(snowflake.nextId());
        inventoryReceiveRecord.setBranchId(dto.getBranchId());
        inventoryReceiveRecord.setInventoryId(dto.getId());
        inventoryReceiveRecord.setCount(dto.getCount());
        inventoryReceiveRecord.setRemark(dto.getRemark());
        SecUser secUser = secUserMapper.selectById(dto.getUserId());
        if (secUser == null) {
            throw new BusinessException("当前用户不存在");
        }
        inventoryReceiveRecord.setUserName(secUser.getUsername());
        inventoryReceiveRecordMapper.insert(inventoryReceiveRecord);
        return ApiResponse.ofSuccess();
    }

}
